/*
	Tournament-o-Matic
	Saves the clickmonkey
	Author: Eike, based on Spockholm code.
	Thanks to Martin and Pete for helping, testing and everything!
	Thanks to Jennifer for testing!
*/
/*
	Todo/History:
	
	#v1.01
	- warning if stamina is insufficient
	- save settings

	#v1.02
	- add betting

	
	#v1.03
	- parse brackets (opponents, win/loose)
	
	#

*/

javascript: (function () {
    var version = 'Tournament-o-Matic v1.01';
    var stopimg = '';

    try {
        if (document.getElementById('app10979261223_iframe_canvas')) {
            window.location.href = document.getElementById('app10979261223_iframe_canvas').src;
            return;
        } else if (document.getElementsByClassName('canvas_iframe_util')[0]) {


            window.location.href = document.getElementsByClassName('canvas_iframe_util')[0].src;
            return;
        } else if (document.getElementById('some_mwiframe')) {


            //new mafiawars.com iframe
            window.location.href = document.getElementById('some_mwiframe').src;
            return;
        } else {


            document.body.parentNode.style.overflowY = "scroll";
            document.body.style.overflowX = "auto";
            document.body.style.overflowY = "auto";
            try {
                document.evaluate('//div[@id="mw_city_wrapper"]/div', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0).style.margin = "auto";
                if (typeof FB != 'undefined') {
                    FB.CanvasClient.stopTimerToSizeToContent;
                    window.clearInterval(FB.CanvasClient._timer);
                    FB.CanvasClient._timer = -1;
                }
                document.getElementById('snapi_zbar').parentNode.parentNode.removeChild(document.getElementById('snapi_zbar').parentNode);
                document.getElementById('mw_zbar').parentNode.removeChild(document.getElementById('mw_zbar'));
            } catch (fberr) {}


        }

        /**
         * from http://binnyva.blogspot.com/2005/10/dump-function-javascript-equivalent-of.html
         * only used for debugging
         * Function : dump()
         * Arguments: The data - array,hash(associative array),object
         *    The level - OPTIONAL
         * Returns  : The textual representation of the array.
         * This function was inspired by the print_r function of PHP.
         * This will accept some data as the argument and return a
         * text that will be a more readable version of the
         * array/hash/object that is given.
         */

        function dump(arr, level) {
            var dumped_text = "";
            if (!level) level = 0;

            //The padding given at the beginning of the line.
            var level_padding = "";
            for (var j = 0; j < level + 1; j++) level_padding += "    ";

            if (typeof(arr) == 'object') { //Array/Hashes/Objects
                for (var item in arr) {
                    var value = arr[item];

                    if (typeof(value) == 'object') { //If it is an array,
                        dumped_text += level_padding + "'" + item + "' ...\n";
                        dumped_text += dump(value, level + 1);
                    } else {
                        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
                    }
                }
            } else { //Stings/Chars/Numbers etc.
                dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
            }
            return dumped_text;
        }

        function unix_timestamp() {
            return parseInt(new Date().getTime().toString().substring(0, 10))
        }

        // from Yevgen Silant'yev, http://joyka.pp.ua/
        function getMWURL() {
            str = document.location;
            str = str.toString();
            beg = str.substring(0, str.indexOf('?') + 1);
            str = str.substring(str.indexOf('?') + 1);
            str = str.split('&');
            mid = '';
            for (var i = 0; i < str.length; i++) {
                if (str[i].indexOf('sf_xw_') == 0) {
                    mid = mid + str[i] + '&';
                }
            }
            return beg + mid;
        }
	function saveForm(cookiename) {
		tagname='savecookie';
		var output=new Object();
        var inputs = $(':input[name="'+tagname+'"]');
        for (var i=0;i<inputs.length;i++) {
        	switch(inputs[i].type) {
				case 'select-one':
				output[inputs[i].id]=inputs[i].selectedIndex;
				break;
				case 'text':
				output[inputs[i].id]=inputs[i].value;
				break;
				case 'checkbox':
				output[inputs[i].id]=inputs[i].checked;
				break;
				default: alert(inputs[i].type);
			}
        }
		createCookie(cookiename,JSON.stringify(output));
	}

	function loadForm(cookiename) {
		cookie=readCookie(cookiename);
		input=JSON.parse(cookie);
		for(name in input) {
			try {
				var el=$(':input[id="'+name+'"]')[0];
			if(el){
				switch (el.type) {
					case 'select-one':
						el.selectedIndex=input[name];
					break;
					case 'text':
						el.value=input[name];
					break;
					case 'checkbox':
						el.checked=input[name];
					break;
				}
			}				
			} catch(e) { }	
		}
	}

        if (navigator.appName == 'Microsoft Internet Explorer') {
            alert('You are using Internet Explorer, this bookmarklet will not work.\nUse Firefox or Chrome instead.');
            return;
        }
        var MWURL = getMWURL();
        var sf_xw_sig = ''; //sf_xw_sig=([a-fA-F0-9]+)/.exec(document.body.innerHTML)[1];
        var userid = /sf_xw_user_id': '(.+)'/.exec(document.body.innerHTML)[1];
        var uid = /p\|(\d+)/.exec(userid)[1];
        var fb_userid = FB.Facebook.apiClient.get_session().uid + '';
        var run = 1,
            xmlHTTP, content = document.getElementById('content_row'),
            debug = false,
            specialmsg = '',
            output = '',
            x = 0,
            second = false,
            last_url = null,
            retries = 1,
            tmpkey = false,
            totalfriends = 0,
            combinedloot = '',
            done = 0,
            list = 0,
            ach = 1,
            mw_url = 'http://apps.facebook.com/inthemafia/profile.php?id=%7B%22user%22%3A%22ID%22%7D',
            color = '#BCD2EA',
            fb_url = 'http://www.facebook.com/profile.php?id=';
        var cb = '';
        tmp_key = '';

        var userid = /sf_xw_user_id=([a-z]\|[0-9]+)/.exec(document.body.innerHTML)[1],
            person_id = /([a-z]\|([0-9]+))/.exec(userid)[2];


        // createCookie from Vern's Toolkit http://vern.com/mwtools/
        function createCookie(name, value) {
            // expire one month from now
            var expires = new Date();
            expires.setDate(expires.getDate() + 30);
            document.cookie = name + "=" + value + ";expires=" + expires.toGMTString() + "; path=/";
        }

        // readCookie from Vern's Toolkit http://vern.com/mwtools/
        function readCookie(name) {
            var i, cookie, nameEQ = name + "=",



                cookieArray = document.cookie.split(";");
            for (i = 0; i < cookieArray.length; i++) {
                cookie = cookieArray[i];
                while (cookie.charAt(0) == ' ')
                cookie = cookie.substring(1, cookie.length);
                if (cookie.indexOf(nameEQ) == 0) return cookie.substring(nameEQ.length, cookie.length);


            }
            return null;
        }


		var config_html =
		'<style type="text/css">'+
			'.messages img{margin:0 10px;vertical-align:top; margin-bottom:10px;};'+
			'#close{display:inline};'+	
		'</style>'+
		'<form name="spockform">'+
			'<table class="messages" style="margin-bottom: 5px;">'+
				'<tr><td></td><td align="right" style="text-align:right;font-size:1.1em;">'+version+' - <a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">Spockholm Mafia Tools</a> - <a href="http://www.spockholm.com/mafia/donate.php?Tournament-o-Matic" alt="Donate Coffee/Beer" target="_blank">Donate</a> - <a href="#" id="close" onclick="javascript:$(\'#spockdiv\').remove();return false;"><img src="'+stopimg+'" alt="Close" title="Close" width="16" height="16"></a></td></tr>'+
				'<tr><td colspan="2"><hr /></td></tr>'+
				'<tr><td>Weight Class:</td><td><select id="spoprotary" name="savecookie">'+
				'<option value="0">Flyweight</option>'+			
				'<option value="1">Bantamweight</option>'+			
				'<option value="2">Featherweight</option>'+
				'<option value="3">Lightweight</option>'+
				'<option value="4">Welterweight</option>'+
				'<option value="5">Middleweight</option>'+
				'<option value="6">Cruiserweight</option>'+
				'<option value="7">Heavyweight</option>'+
				'<option value="8">Auto highest possible</option>'+
				'</select></td></tr>'+
				'<tr style="display:none;"><td>Bet:</td><td><select id="spopbetamount" name="savecookie"><option value=0>nothing</option><option value=1>100 V$</option><option value=2>1.000 V$</option><option value=3>10.000 V$</option><option value=4>100.000 V$</option></select> on <input id="spopbets" type="text" value="3" size="2" name="savecookie" />:1 or better</td></tr>'+
				'<tr><td>Stats:</td><td>Save statistics in cookie: <input id="spopsave" type="checkbox" checked="1" name="savecookie" /></td></tr>'+
				'<tr><td></td><td></td></tr>'+
				'<tr><td></td><td><a class="sexy_button" style="float:none;display:inline;" id="spstart">Go for the win!</a></td></tr>'+

			'</table>'+
		'</form>';

		var running_html =
		'<style type="text/css">'+
			'.messages img{margin:0 10px;vertical-align:top;} '+
			'.tmn { min-height:200px;max-height:200px;min-width:240px;max-width:240px;border:1px solid white; } '+
			'#tmn1 { border: 3px solid green; display:none;}'+
			'#tmn2 { border: 3px solid orange; display:none;}'+
			'#tmn3 { border: 3px solid red; display:none;}'+
			'#tmn1caption { background-color:green; min-width:240px;max-width:240px; text-align:center; } '+
			'#tmn2caption { background-color:orange; min-width:240px;max-width:240px; text-align:center; } '+
			'#tmn3caption { background-color:red; min-width:240px;max-width:240px; text-align:center;} '+
			'#close{display:inline; } '+	
		'</style>'+
		'<form name="spockform">'+
			'<table class="messages" style="margin-bottom: 5px;">'+
				'<tr><td></td><td align="right" colspan="2" style="text-align:right;font-size:1.1em;">'+version+' - <a href="http://www.spockholm.com/mafia/bookmarklets.php" target="_top">Spockholm Mafia Tools</a> - <a href="http://www.spockholm.com/mafia/donate.php?Tournament-o-Matic" alt="Donate Coffee/Beer" target="_blank">Donate</a> - <a href="#" id="close" onclick="javascript:$(\'#spockdiv\').remove();return false;"><img src="'+stopimg+'" alt="Close" title="Close" width="16" height="16"></a></td></tr>'+
				'<tr><td colspan="2"><hr /></td></tr>'+
				'<tr><td colspan="2"><div id="spimages" style="text-align:center; display:block"></div></td></tr>'+
				'<tr><td colspan="2">'+
				'<table><tr style="min-height:500px;max-height:500px;min-width:930px;max-width:930px;border:1px solid white;">'+
					'<td><div id="tmn1" class="tmn"><div id="tmn1caption">Regional</div>'+
					'<div style="text-align:center;" id="tmnresult1"></div>'+
					'<div style="text-align:center;" id="tmnloot1"></div>'+
					'</div></td>'+
					'<td><div id="tmn2" class="tmn"><div id="tmn2caption">National</div>'+
					'<div style="text-align:center;" id="tmnresult2"></div>'+
					'<div style="text-align:center;" id="tmnloot2"></div>'+
					'</div></td>'+
					'<td><div id="tmn3" class="tmn"><div id="tmn3caption">World</div>'+
					'<div style="text-align:center;" id="tmnresult3"></div>'+
					'<div style="text-align:center;" id="tmnloot3"></div>'+
					'</div></td>'+
				'</tr></table>'+
				'</td></tr>'+
				
				'<tr><td>Action:</td><td><span id="sprunaction"></span></td></tr>'+
				'<tr><td>Stats:</td><td>'+
				'<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/buy_stamina_75x75.png" width=32 height=32 /><span id="spstamina" style="font-size:32px;" class="good">0</span> '+
				'<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/mw_tournaments_popup-icons-xp.png" /> <span id="splootexp" style="font-size:32px;" class="good">0</span> '+
				'<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/mw_tournaments_popup-icons-fan.png" /> <span id="splootfans" style="font-size:32px;" class="good">0</span>'+
				'<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/mw_tournaments_popup-icons-chip.png" /> <span id="splootvdollar" style="font-size:32px;" class="good">0</span> '+
				'<img src="http://mwfb.static.zgncdn.com/mwfb/graphics/mw_tournaments_popup-icons-fight.png" /> <span id="splootvcoins" style="font-size:32px;" class="good">0</span> '+
				'</td></tr>'+
				'<tr id="spalltimedisplay"><td>Alltime:</td><td><span id="spresultalltime"></span></td></tr>'+
			'</table>'+
		'</form>';
        //http://mwfb.static.zgncdn.com/mwfb/graphics/mw_tournaments_won-reg.png
        //tournament_result_exp tournament_result_fans tournament_result_tokens tournament_result_chips
        //background: url("http://mwfb.static.zgncdn.com/mwfb/graphics/mw_tournaments_won-world.png") no-repeat scroll center top transparent;	

        function create_div() {
            if (document.getElementById('spockdiv')) {
                document.getElementById('spockdiv').innerHTML = config_html;
            } else {
                var spock_div = document.createElement("div");
                spock_div.id = 'spockdiv';
                spock_div.innerHTML = config_html;
                content.insertBefore(spock_div, content.firstChild);
            }
			loadForm('sptournaments');
        }
        create_div();

        document.getElementById('close').onclick = function (e) {
            run = 0;
            document.getElementById("content_row").removeChild(document.getElementById("spockdiv"));
            return false;
        };

        var stage = 0;
        retry = 0;
        run = 1;

        var datapage = ''; // contains all links
        var exp = 0,
            vcoins = 0,
            fans = 0,
            vdollar = 0,
            stam = 0;

        // params
        var op_savecookie, op_betamount, op_bets, op_rotary;
        var att, def;
        var tclass = 0;
        var at_count = 0,
            at_xp = 0,
            at_stam = 0,
            at_cash = 0,
            at_fans = 0,
            at_vcoins = 0,
            at_win = 0,
            at_lose = 0,
            at_tournament = 0,
            at_regional = 0,
            at_national = 0,
            at_world = 0;


        document.getElementById('spstart').onclick = function (e) {
			saveForm('sptournaments');


            op_savecookie = document.getElementById('spopsave').checked;
            op_betamount = document.getElementById('spopbetamount').value;
            op_bets = document.getElementById('spopbets').value;
            op_rotary = document.getElementById('spoprotary').value;

            document.getElementById('spockdiv').innerHTML = running_html;






            if (!op_savecookie) {
                document.getElementById("spalltimedisplay").style.display = 'none';
            }

            sprun();
            return false;
        };

        var stages = {
            0: 'Loading start page',
            1: 'Select Weightclass',
            2: 'Step into the ring',
            3: 'Skip bets',
            4: 'Go ahead',
            5: 'Skip bets again',
            6: 'Go ahead again',
            7: 'Fight',
            8: 'Get Results',
            9: 'Step into the ring',
            10: 'Skip bets',
            11: 'Go ahead',
            12: 'Skip bets again',
            13: 'Go ahead again',
            14: 'Fight',
            15: 'Get Results',
            16: 'Step into the ring',
            17: 'Skip bets',
            18: 'Go ahead',
            19: 'Skip bets again',
            20: 'Go ahead again',
            21: 'Fight',
            22: 'Get Results',
            23: 'Finished'
        };

        function saveData() {
            if (op_savecookie) {
                cook = at_count + '#' + at_xp + '#' + at_stam + '#' + at_cash + '#' + at_fans + '#' + at_vcoins + '#' + at_win + '#' + at_lose + '#' + at_tournament + '#' + at_regional + '#' + at_national + '#' + at_world;
                createCookie('sptournament', cook);
            }
        }

        function loadData() {
            cook = readCookie('sptournament');
            try {
                carr = cook.split('#');
                at_count = parseInt(carr[0]);
                at_xp = parseInt(carr[1]);
                at_stam = parseInt(carr[2]);
                at_cash = parseInt(carr[3]);
                at_fans = parseInt(carr[4]);
                at_vcoins = parseInt(carr[5]);
                at_win = parseInt(carr[6]);
                at_lose = parseInt(carr[7]);
                at_tournament = parseInt(carr[8]);
                at_regional = parseInt(carr[9]);
                at_national = parseInt(carr[10]);
                at_world = parseInt(carr[11]);



            } catch (e) {}


        }
        loadData();

        function displayData() {
            document.getElementById('spresultalltime').innerHTML = 'XP: ' + at_xp + ', STAM;' + at_stam + ', XP/STAM ratio:' + (at_xp / at_stam).toFixed(2) + ', V$: ' + at_cash + ', FANS:' + at_fans + ', VCOINS:' + at_vcoins + '<br>';




            //		document.getElementById('spresultalltime').innerHTML+=at_count+'#'+at_xp+'#'+at_stam+'#'+at_cash+'#'+at_fans+'#'+at_vcoins+'#'+at_win+'#'+at_lose+'#'+at_tournament+'#'+at_regional+'#'+at_national+'#'+at_world;
        }

        function stopAndError(errormsg) {
            document.getElementById('sprunaction').innerHTML = '<font color=red><b>' + errormsg + '</b></font>';
            run = 0;
        }

        function update(msg, color) {
            if (color == null) {
                color = 'white';
            }
            document.getElementById('sprunaction').innerHTML = '<font color="' + color + '"><b>' + msg + '</b></font>';
        }

        function localupdate(msg, color) {
            if (color == null) {
                color = 'green';
            }
            try {
                document.getElementById('tmnresult' + tclass).innerHTML = '<font color="' + color + '"><b>' + msg + '</b></font>';
            } catch (e) {}

        }

        function showloot(loot, attplus, defplus) {
            return '<img src="' + (loot['image'] ? 'http://mwfb.static.zgncdn.com/mwfb/graphics/' + loot['image'] : 'http://mwfb.static.zgncdn.com/mwfb/graphics/collections/standard/standard_75x75_' + loot['base_image']) + '" /><br>' + loot['name'] + (loot['attack'] ? '<br><span class="attack">' + loot['attack'] + '</span>' + (attplus > 0 ? '(+' + attplus + ')' : '') + '<br><span class="defense">' + loot['defense'] + '</span>' + (defplus > 0 ? '(+' + defplus + ')' : '') : '');





        }

        // http://mwfb.static.zgncdn.com/mwfb/graphics/collections/standard/collect_belt2_01.gif
        // http://mwfb.static.zgncdn.com/mwfb/graphics/collections/standard/standard_75x75_collect_belt2_01.gif
/*
		extract tmp and cb from the main page, then create the link-url 	
	*/

        function getLink(action, xtra) {
            if (!xtra) {
                xtra = '';
            }
            tmp = '';
            cb = '';

            rx = new RegExp('xw_action=' + action + '&xw_city=5&tmp=([a-f0-9]{32})&cb=([a-f0-9]{32})');
            if (m = rx.exec(datapage)) {
                tmp = m[1];
                cb = m[2];
            }
            return 'html_server.php?xw_controller=tournament&xw_action=' + action + '&xw_city=5&tmp=' + tmp + '&cb=' + cb + '&xw_person=' + uid + xtra + '&xw_client_id=8';
        }


        function sprun() {
            // select stage and take apropriate action
            if (retry > 3) { // not yet implemented
                stopAndError('Too many retries, giving up :(');
            }
            if (run == 0) {
                return;
            }
            update(stages[stage]);
            switch (stage) {
            case 0:
                request(getLink('view'));
                break;
            case 1:
                request(getLink('pageWeightClass'));
                break;
            case 2:
                request(getLink('pageTiers', '&rotary=' + op_rotary));
                break;
            case 3:
            case 5:
            case 10:
            case 12:
            case 17:
            case 19:
                request(getLink('pageBet'));
                break;
            case 4:
            case 6:
            case 11:
            case 13:
            case 18:
            case 20:
                request(getLink('pageBrackets'));
                break;
            case 7:
            case 14:
            case 21:
                request(getLink('fight'));
                break;
            case 8:
            case 15:
            case 22:
                request(getLink('pageResults'));
                break;
            case 9:
            case 16:
                request(getLink('pageTiers'));
                break;
            }




        }

        function parse_result(msg) {
            var m;

            try {
                msg_json = JSON.parse(msg);
            } catch (e) {
                msg_json = '';
            }

            switch (stage) {
            case 0:
                datapage = msg;
                // check if city is ok
                active_city = parseInt(/current_city_id.*?(\d+)/.exec(msg)[1]);

                if (active_city != 5) {
                    update('Travel to Vegas', 'yellow');
                    travel(5);
                    return;
                }

                // check if tournament is available		
                if (/not available/.test(msg)) {
                    stopAndError('Tournament is not yet available!');
                }

                stage++;
                break;
            case 1:
                // check if weight class is available
                try {
                    js2 = JSON.parse(msg_json['weightClasses']);
                    if (op_rotary == 8) { // select highest unlocked
                        var highest = 0;
                        for (var i = 0; i < 8; i++) {
                            if (js2[i]['beltCssClass'] == 'unlocked') {
                                highest = i;
                            }
                        }
                        op_rotary = highest;
                    }

                    if (js2[op_rotary]['beltCssClass'] != 'unlocked') {
                        stopAndError('Class is locked. Please select another.');
                    } else {
                        document.getElementById('spimages').innerHTML += '<img src="' + js2[op_rotary]['image'] + '" /><br>' + js2[op_rotary]['fullName'];
                    }
                } catch (e) {
                    stopAndError('Tournament is not yet available!');
                }

                //			stopAndError('Dammit, Testing mode');
                stage++;
                break;
            case 8:
            case 15:
            case 22:
                switch (msg_json['result']) {
                case 2:
                    localupdate('Lost quarter finals', 'red');

                    stopAndError('Tournament ended');
                    break;
                case 3:
                    localupdate('Lost semi finals', 'red');

                    stopAndError('Tournament ended');
                    break;
                case 4:
                    localupdate('Lost final', 'red');
                    stopAndError('Tournament ended');
                    break;
                case 5:
                    localupdate('Tournament won!', 'green');

                    break;
                }
                // read loot
                if (msg_json['rewards']['itemAwarded'] != null) {
                    att_new = parseInt(msg_json['fightbar']['group_atk'].replace(/,/, ''));
                    def_new = parseInt(msg_json['fightbar']['group_def'].replace(/,/, ''));
                    document.getElementById('tmnloot' + tclass).innerHTML += showloot(msg_json['rewards']['itemAwarded'], att_new - att, def_new - def);
                } else {
                    document.getElementById('tmnloot' + tclass).innerHTML += 'No loot awarded!';
                }
                // read stats
                exp += parseInt(msg_json['rewards']['exp']);
                at_xp += parseInt(msg_json['rewards']['exp']);
                vcoins += parseInt(msg_json['rewards']['vcoins']);
                at_vcoins += parseInt(msg_json['rewards']['vcoins']);
                vdollar += parseInt(msg_json['rewards']['chips']);
                at_cash += parseInt(msg_json['rewards']['chips']);
                fans += parseInt(msg_json['rewards']['fans']);
                at_fans += parseInt(msg_json['rewards']['fans']);




                // update stats
                document.getElementById('splootexp').innerHTML = exp;
                document.getElementById('splootvcoins').innerHTML = vcoins;
                document.getElementById('splootvdollar').innerHTML = vdollar;
                document.getElementById('splootfans').innerHTML = fans;
                displayData();
                saveData();
                stage++;
                break;
            case 2:
            case 9:
            case 16:

                try {
                    js2 = JSON.parse(msg_json['playerProgress']);

                    st = js2['regional']['cost_stamina'];
                    ch = js2['regional']['cost_chips'];
                    tclass = 1;
                    if (js2['regional']['is_champion'] == true) {
                        st = js2['national']['cost_stamina'];
                        ch = js2['national']['cost_chips'];
                        tclass = 2;
                        if (js2['national']['is_champion'] == true) {
                            st = js2['world']['cost_stamina'];
                            ch = js2['world']['cost_chips'];
                            tclass = 3;
                        }
                    }
					// check money/stam
					if(msg_json.user_fields.user_cash<ch) {
						stopAndError('Insufficient Cash!');
						return;
					}
					if(msg_json.user_fields.user_stamina<st) {
						stopAndError('Insufficient Stamina!');
						return;
					}
				
                    document.getElementById('tmn' + tclass).style.display = 'block';
                    localupdate('Starting tournament...');
                    vdollar -= ch;
                    at_cash -= ch;
                    stam += st;
                    at_stam += st;
                    document.getElementById('splootvdollar').innerHTML = vdollar;
                    document.getElementById('spstamina').innerHTML = stam;
                    displayData();


                } catch (e) {}


                stage++;
                break;
            case 4:
            case 6:
            case 11:
            case 13:
            case 18:
            case 20:
                try {
                    att = parseInt(msg_json['fightbar']['group_atk'].replace(/,/, ''));
                    def = parseInt(msg_json['fightbar']['group_def'].replace(/,/, ''));
                } catch (e) {}


                stage++;
                break;
            default:
                stage++;
                break;
            }

            if (run == 1) {
                setTimeout(sprun, 1000);
            }
        }

        function travel(destination) {
            var userid = /sf_xw_user_id=([a-z]\|[0-9]+)/.exec(document.body.innerHTML)[1],
                personid = /([a-z]\|([0-9]+))/.exec(userid)[2];

            var cb = userid + unix_timestamp();
            var params = {
                'destination': destination,
                'from': 'hospital',
                'tmp': '',
                'cb': cb,
                'xw_person': personid,
                'xw_client_id': 8,
                'ajax': 1,
                'liteload': 1,
                'sf_xw_sig': local_xw_sig,
                'sf_xw_user_id': userid
            };
            $.ajax({
                type: 'POST',
                data: params,
                url: 'http://facebook.mafiawars.com/mwfb/remote/html_server.php?xw_controller=travel&xw_action=travel',
                success: function (response) {
                    try {
                        sprun();
                        return;
                    } catch (output_problem) {


                        alert('Error in travel(): ' + output_problem);
                    }
                }
            });
        }


        function request(url) {
            if (run == 1) {

                var preurl = 'http://facebook.mafiawars.com/mwfb/remote/';
                //			cb = userid+unix_timestamp();
                ts = unix_timestamp();
                var params = {
                    'ajax': 1,
                    'liteload': 1,
                    'sf_xw_user_id': userid,
                    'sf_xw_sig': local_xw_sig,
                    'xw_client_id': 8,
                    'skip_req_frame': 1
                };
                $.ajax({
                    type: "POST",
                    url: preurl + url,
                    //+'&cb='+cb+'&tmp='+tmp_key,

                    data: params,
                    //dataType: 'json',
                    cache: false,
                    success: function (msg) {
                        parse_result(msg);
                    },
                    error: function (request, status, error) {
                        retry++;
                        sprun();
                    }
                });

                //setTimeout(state_change, 4000);
            } else {
                msg('Paused searching.');
            }
            last_url = url;
        }


        //testing to add analytics


        function loadContent(file) {
            var head = document.getElementsByTagName('head').item(0)
            var scriptTag = document.getElementById('loadScript');
            if (scriptTag) head.removeChild(scriptTag);
            script = document.createElement('script');
            script.src = file;
            script.type = 'text/javascript';
            script.id = 'loadScript';
            head.appendChild(script);
        }
        loadContent('http://www.google-analytics.com/ga.js');
        try {
            var pageTracker = _gat._getTracker("UA-8435065-3");
            pageTracker._trackPageview();
            pageTracker._trackPageview("/script/Tournament-o-Matic");
        } catch (err) {}
        //end analytics

    } //end try
    catch (mainerr) {
        var spock_div = document.getElementById('spockdiv');
        if (spock_div) {
            spock_div.innerHTML = '';
        }
        alert('Some error occured.\nDid you run on an unframed MW page?\nIf you did, report the message below (NOT THIS TEXT) to Spockholm:\n\n' + version + '\n' + mainerr);
    }


























}())